package com.itheima.day05.shop.storage;

import com.itheima.day05.shop.pojo.Product;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class ProductFileStorage {
    private AtomicLong idGenerator = new AtomicLong(1);
    private static final URL url = ProductFileStorage.class.getClassLoader().getResource("products.dat");
    public List<Product> readAllProducts() {
        List<Product> products = new ArrayList<>();
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(url.toURI())))) {
            products = (List<Product>) ois.readObject();
        } catch (Exception e) {
            // 文件不存在，返回空列表
        }
        return products;
    }

    public Optional<Product> readProduct(Long id) {
        List<Product> products = readAllProducts();
        return products.stream()
                .filter(product -> product.getId().equals(id))
                .findFirst();
    }

    public Product saveProduct(Product product) {
        List<Product> products = readAllProducts();
        if (product.getId() == null) {
            product.setId(idGenerator.getAndIncrement());
        }
        products.removeIf(p -> p.getId().equals(product.getId()));
        products.add(product);
        writeProducts(products);
        return product;
    }

    public void deleteProduct(Long id) {
        List<Product> products = readAllProducts();
        products.removeIf(product -> product.getId().equals(id));
        writeProducts(products);
    }

    private void writeProducts(List<Product> products) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(url.toURI())))) {
            oos.writeObject(products);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}